import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';
import { Injectable } from '@nestjs/common';
import { ResultData } from 'src/common/utils/result';
import { CreateSessionDto, QuerySessionDto, UpdateSessionDto } from './dto/session.dto';
import { SessionEntity } from './entities/session.entity';
import { isEmpty } from 'src/common/utils';

@Injectable()
export class SessionService {
  constructor(
    @InjectRepository(SessionEntity)
    private readonly sessionEntityRep: Repository<SessionEntity>,
  ) {}

  async create(createSessionDto: CreateSessionDto) {
    const res = await this.sessionEntityRep.save(createSessionDto);
    return ResultData.ok(res);
  }

  // 使用原生SQL进行多表联查
  async findSessionInfo(sessionId: number) {
    const sql = `
        SELECT
            su.phonenumber, s.user_id AS userId, ci.parent_id AS parentId
        FROM
            session s
                JOIN
            child_info ci ON s.user_id = ci.user_id
                JOIN
            sys_user su ON ci.parent_id = su.user_id
        WHERE
            s.id = ?
          AND s.del_flag = '0'
          AND ci.del_flag = '0'
          AND su.del_flag = '0';
    `;

    // 执行原生SQL查询
    return await this.sessionEntityRep.query(sql, [sessionId]);
  }

  async findAll(query: QuerySessionDto) {
    const entity = this.sessionEntityRep.createQueryBuilder('entity');
    entity.where({ delFlag: '0' });
    if (!isEmpty(query.id)) {
      entity.andWhere('entity.id = :id', { id: query.id });
    }
    if (!isEmpty(query.userId)) {
      entity.andWhere('entity.userId = :userId', { userId: query.userId });
    }
    if (!isEmpty(query.delFlag)) {
      entity.andWhere('entity.delFlag = :delFlag', { delFlag: query.delFlag });
    }
    if (!isEmpty(query.createTime)) {
      entity.andWhere('entity.createTime BETWEEN :start AND :end', { start: query.createTime[0], end: query.createTime[1] });
    }
    if (!isEmpty(query.updateTime)) {
      entity.andWhere('entity.updateTime BETWEEN :start AND :end', { start: query.updateTime[0], end: query.updateTime[1] });
    }
    entity.select(['entity.id', 'entity.userId', 'entity.title', 'entity.delFlag', 'entity.createTime', 'entity.updateTime']);

    if (query.orderByColumn && query.isAsc) {
      const key = query.isAsc === 'ascending' ? 'ASC' : 'DESC';
      entity.orderBy(`entity.${query.orderByColumn}`, key);
    }

    if (query.pageNum && query.pageSize) {
      entity.skip(query.pageSize * (query.pageNum - 1)).take(query.pageSize);
    }

    const [list, total] = await entity.getManyAndCount();

    return ResultData.ok({
      list,
      total,
    });
  }

  async findOne(id: number) {
    const res = await this.sessionEntityRep.findOne({
      where: {
        delFlag: '0',
        id: id,
      },
    });
    return ResultData.ok(res);
  }

  async findOneById(id: number) {
    return await this.sessionEntityRep.findOne({
      where: {
        delFlag: '0',
        id: id,
      },
    });
  }

  async findLatest(userId: number) {
    const res = await this.sessionEntityRep.findOne({
      where: {
        delFlag: '0',
        userId: userId,
      },
      order: {
        id: 'DESC',
      },
    });
    return ResultData.ok(res);
  }

  async update(updateSessionDto: UpdateSessionDto) {
    const res = await this.sessionEntityRep.update({ id: updateSessionDto.id }, updateSessionDto);
    return ResultData.ok({ value: res.affected >= 1 });
  }

  async remove(id: number) {
    const res = await this.sessionEntityRep.update(
      { id: id },
      {
        delFlag: '1',
      },
    );
    return ResultData.ok({ value: res.affected >= 1 });
  }
}
